#include <iostream>
#include <vector>
#include <cstdio> 
#include <queue>

#define in read()
#define fi first
#define se second
#define pb push_back

using namespace std;

typedef long long ll;
typedef double db;
typedef vector < int >  vec;
typedef pair < int , int > pii;

int read() {
  int x = 0; bool f = 0; char ch = getchar(); while(!isdigit(ch)) f |= ch == '-',ch = getchar();
  while(isdigit(ch)) x = x * 10 + (ch ^ 48),ch = getchar(); return f ? -x : x;
}

const int N = 3e5 + 10;

int n;
priority_queue < int , vector < int > , greater < int > > q;

int main() {
#ifndef ONLINE_JUDGE
    freopen("1.in","r",stdin);
#endif
    n = in; ll ans = 0;
    for(int i = 1;i <= n;i++) {
	int a = in; q.push(a);
	if(a > q.top()) ans += a - q.top(),q.pop(),q.push(a);
    } printf("%lld\n",ans); return 0;
} 
